'''
陈超依 19377189
现代程序设计第三周作业
'''

from os import error
import jieba
jieba.load_userdict(r"E:/Py_Programs/week3/anger.txt")
jieba.load_userdict(r"E:/Py_Programs/week3/disgust.txt")
jieba.load_userdict(r"E:/Py_Programs/week3/fear.txt")
jieba.load_userdict(r"E:/Py_Programs/week3/joy.txt")
jieba.load_userdict(r"E:/Py_Programs/week3/sadness.txt")
import time

class Comment:
    def __init__(self, word, times, place):
        self.word = word
        self.times = time.strptime(times, "%a %b %d %H:%M:%S +0800 %Y")
        self.place = place
        self.emo = emotion(self)

Lcomment = []

def data_cleansing():
    '''对微博数据进行清洗'''
    Comments = open("E:/Py_Programs/week3/weibo.txt",mode='r',encoding='utf-8').readlines()
    StopWords = open("E:/Py_Programs/week3/StopWords_list.txt",mode='r',encoding='utf-8').read()
    StopWords = StopWords.split("\n")
    for each in Comments:
        part = each.split('\t')
        word = jieba.lcut(((part[0]).split(' 我在'))[0],cut_all = True)
        for i in range(len(word)):
            if (word[i] in StopWords):
                word[i] = ' '
        for i in range(word.count(' ')):
            word.remove(' ')
        times = part[1]
        place = (part[2])[:-1]  #删除末尾的换行符
        cleaned = Comment(word, times, place)
        Lcomment.append(cleaned)

def emotion(comment: Comment):
    '''判断输入评论的情绪类型（认为评论具有单一情绪）'''
    Lemotion = {}
    anger = (open("E:/Py_Programs/week3/anger.txt",mode='r',encoding='utf-8').read()).split('\n')
    for angerword in anger:
        Lemotion[angerword] = 'anger'
    disgust = (open("E:/Py_Programs/week3/disgust.txt",mode='r',encoding='utf-8').read()).split('\n')
    for disgustword in disgust:
        Lemotion[disgustword] = 'disgust'
    fear = (open("E:/Py_Programs/week3/fear.txt",mode='r',encoding='utf-8').read()).split('\n')
    for fearword in fear:
        Lemotion[fearword] = 'fear'
    joy = (open("E:/Py_Programs/week3/joy.txt",mode='r',encoding='utf-8').read()).split('\n')
    for joyword in joy:
        Lemotion[joyword] = 'joy'
    sadness = (open("E:/Py_Programs/week3/sadness.txt",mode='r',encoding='utf-8').read()).split('\n')
    for sadnessword in sadness:
        Lemotion[sadnessword] = 'sadness'
    def emotion_mix():
        '''逐条分析各条微博情绪（认为情绪是单一的）'''
        L = [0, 0, 0, 0, 0]
        for eword in comment.word:
            if (eword in Lemotion):
                if (Lemotion[eword] == 'anger'):
                    L[0] = (L[0] + 1)
                if (Lemotion[eword] == 'disgust'):
                    L[1] = (L[1] + 1)
                if (Lemotion[eword] == 'fear'):
                    L[2] = (L[2] + 1)
                if (Lemotion[eword] == 'joy'):
                    L[3] = (L[3] + 1)
                if (Lemotion[eword] == 'sadness'):
                    L[4] = (L[4] + 1)
        Lmax = max(L)
        if (Lmax == 0):
            return 'NoEmotion'
        if (L[0] == Lmax ):
            if (L[1] < Lmax and L[2] < Lmax):
                if (L[3] < Lmax and L[4] < Lmax):
                    return 'anger'
        if (L[1] == Lmax ):
            if (L[0] < Lmax and L[2] < Lmax):
                if (L[3] < Lmax and L[4] < Lmax):
                    return 'disgust'
        if (L[2] == Lmax ):
            if (L[0] < Lmax and L[1] < Lmax):
                if (L[3] < Lmax and L[4] < Lmax):
                    return 'fear'
        if (L[3] == Lmax ):
            if (L[0] < Lmax and L[1] < Lmax):
                if (L[2] < Lmax and L[4] < Lmax):
                    return 'joy'
        if (L[4] == Lmax ):
            if (L[0] < Lmax and L[1] < Lmax):
                if (L[2] < Lmax and L[3] < Lmax):
                    return 'sadness'
        return 'NoEmotion'
    return emotion_mix()

def emotion_time(emo: str, mode: str):
    '''
    返回情绪的时间模式
    emo in ['anger', 'disgust', 'fear', 'joy', 'sadness']
    mode in ['hour', 'day' ]
    '''
    if (emo not in ['anger', 'disgust', 'fear', 'joy', 'sadness']):
        return error
    if (mode not in ['hour', 'day']):
        return error
    Dictemo = {}
    Dictallemo = {}
    if (mode == 'day'):
        for ecomment in Lcomment:
            if (ecomment.emo == 'NoEmotion'):
                continue
            group = time.strftime('%d',ecomment.times)
            if(group in Dictallemo):
                Dictallemo[group] = Dictallemo[group] + 1
                if (ecomment.emo == emo):
                    Dictemo[group] = Dictemo[group] + 1
            else:
                Dictallemo[group] = 1
                if (ecomment.emo == emo):
                    Dictemo[group] = 1
                else:
                    Dictemo[group] = 0
    if (mode == 'hour'):
        for ecomment in Lcomment:
            if (ecomment.emo == 'NoEmotion'):
                continue
            group = time.strftime('%d %H',ecomment.times)
            if(group in Dictallemo):
                Dictallemo[group] = Dictallemo[group] + 1
                if (ecomment.emo == emo):
                    Dictemo[group] = Dictemo[group] + 1
            else:
                Dictallemo[group] = 1
                if (ecomment.emo == emo):
                    Dictemo[group] = 1
                else:
                    Dictemo[group] = 0
    for i in Dictemo:
        Dictemo[i] = (Dictemo[i])/(Dictallemo[i])
    print(Dictemo)

def emotion_place(emo: str, center: list, step:float):
    '''
    返回情绪的空间分布
    emo in ['anger', 'disgust', 'fear', 'joy', 'sadness', 'NoEmotion']
    center为中心，step为半径增加步长
    '''
    Dictemo = {}
    Dictallemo = {}
    for ecomment in Lcomment:
        if (ecomment.emo == 'NoEmotion'):
            continue
        place = ((ecomment.place)[1:-1]).split(',')
        place = list(map(float,place))
        group = int((abs(place[0]-center[0])+abs(place[1]-center[1]))/step)
        if(group in Dictallemo):
            Dictallemo[group] = Dictallemo[group] + 1
            if (ecomment.emo == emo):
                Dictemo[group] = Dictemo[group] + 1
        else:
            Dictallemo[group] = 1
            if (ecomment.emo == emo):
                Dictemo[group] = 1
            else:
                Dictemo[group] = 0
    for i in Dictemo:
        Dictemo[i] = (Dictemo[i])/(Dictallemo[i])
    sorted(Dictemo.keys())
    print(Dictemo)

def main():
    data_cleansing()
    emotion_time('joy', 'hour')
    emotion_place('joy',[39,116],0.25)

if __name__ == '__main__':
    main()